package lar.system.opengl;

import java.util.Vector;

import javax.microedition.khronos.opengles.GL11;

import android.util.Log;

import lar.system.engine.UI;
import lar.system.R;

public class GLText implements Drawable
{
	private float[] glPos, glDim;
	private float fontHeight;
	private Vector<GLString> strings;
	private float distanceBetweenLines;
	private boolean newLineAllowed = false;
	
	public GLText(String str, float glPos[], float glDim[], float fontHeight)
	{
		this.fontHeight = fontHeight;
		this.glDim = glDim;
		this.glPos = glPos;
		distanceBetweenLines = fontHeight*0.5f;
		strings = new Vector<GLString>();
		setText(str);
	}
	
	
	private String getWord(String str, int i)
	{
		String arr[] = str.split(" ");
		int w = 0,v = 0;
		for(w = 0; w < arr.length; )
		{
			String sub = arr[w];
			if(sub != null && sub.length() > 0)
			{
				if(v == i) return sub;
				v++;
			}
			w++;
		}
		return null;
	}
	
	public void setIsNewlineAllowed(boolean flag)
	{
		this.newLineAllowed = flag;
	}
	
	public void setColor(GLColor c)
	{
		UI.needRendering = true;
		for(GLString s : strings) s.setColor(c.asFloatArray()); 
	}
	
	public void setText(String str)
	{
		UI.needRendering = true;
		strings.clear();
		int i = 0, lines = 0, words = 0;
		final int charsPerLine = (int)(glDim[0]*2f/fontHeight);
		String buf = new String();
		while(i < str.length())
		{
			String word = getWord(str, words);
			i += word.length()+1;
			if(buf.length()+word.length() > charsPerLine || (word.equals("\n") && newLineAllowed))
			{
				GLString s = new GLString(
						R.drawable.basefont, 
						buf.trim(), 
						new float[]{glPos[0]-glDim[0]+fontHeight/2, glPos[1]+glDim[1]-fontHeight/2-(fontHeight+distanceBetweenLines)*lines}, 
						fontHeight);
				strings.add(s);
				lines++;
				buf = new String();
			}
			
			buf += word + " ";
			words++;
		}
		if(buf.length() > 0)
		{
			GLString s = new GLString(
					R.drawable.basefont, 
					buf, 
					new float[]{glPos[0]-glDim[0]+fontHeight/2, glPos[1]+glDim[1]-fontHeight/2-(fontHeight+distanceBetweenLines)*lines}, 
					fontHeight);
			strings.add(s);
		}
	}
	
	public String getText()
	{
		String ans = new String();
		for(GLString str : strings) ans += str.getAsciiString();
		return ans;
	}
	
	
	public boolean CheckBounds(float gl_x, float gl_y) 
	{
		return false;
	}

	public void Draw(GL11 gl) 
	{
		for(GLString s : strings) s.Draw(gl);
	}

}
